package org.zakariya.stickyheadersapp;

import com.zhy.http.library.OkHttpUtils;
import com.zhy.http.library.callback.GenericsCallback;
import com.zyao89.view.zloading.ZLoadingView;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;
import ohos.agp.utils.Color;
import ohos.agp.window.dialog.ToastDialog;
import okhttp3.Call;
import org.zakariya.stickyheaders.StickyHeaderLayoutManager;
import org.zakariya.stickyheaders.model.HeaderModel;
import org.zakariya.stickyheaders.model.ItemModel;
import org.zakariya.stickyheadersapp.adapter.AddressBookDemoAdapter;
import org.zakariya.stickyheadersapp.model.JsonGenericsSerializator;
import org.zakariya.stickyheadersapp.model.Person;
import org.zakariya.stickyheadersapp.model.RandomUserResults;
import org.zakariya.stickyheadersapp.tool.TopToolUtils;

import java.util.*;
/**
 * AddressBookAbility
 *
 * @since 2021-08-20
 */
public class AddressBookAbility extends Ability {
    private StickyHeaderLayoutManager headerDecor;
    private List<Person> randomUsers = new ArrayList<>();
    private ArrayList<Section> sections = new ArrayList<>();
    private Locale locale = Locale.getDefault();
    private AddressBookDemoAdapter adapter;
    private List<ItemModel> dataList = new ArrayList<>();
    private ListContainer listContainer;
    private ZLoadingView dialog;
    private Image iv_bottom;
    private Image iv_remove;
    private Image iv_menu;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_address_book);
        getWindow().setStatusBarColor(Color.getIntColor("#303F9F"));
        initLoadingView();
        initData();
        initComponent();
    }

    private void initLoadingView() {
        dialog = (ZLoadingView) findComponentById(ResourceTable.Id_loading);
    }

    private void initComponent() {
        iv_bottom = (Image) findComponentById(ResourceTable.Id_iv_bottom);
        iv_remove = (Image) findComponentById(ResourceTable.Id_iv_remove);
        iv_menu = (Image) findComponentById(ResourceTable.Id_iv_menu);
        iv_bottom.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                TopToolUtils.showScrollTool(getContext(), listContainer);
            }
        });

        iv_remove.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                TopToolUtils.showViewTool(getContext(), listContainer, dataList);
            }
        });

        iv_menu.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                TopToolUtils.showReloadTool(getContext(), listContainer);
            }
        });
        Image image = (Image) findComponentById(ResourceTable.Id_icon_back);
        image.setClickedListener(component -> terminateAbility());
        Text headerText = (Text) findComponentById(ResourceTable.Id_sticky_text);
        DependentLayout layout = (DependentLayout) findComponentById(ResourceTable.Id_layout_overlap);
        listContainer = (ListContainer) findComponentById(ResourceTable.Id_list_address_book);
        headerDecor = new StickyHeaderLayoutManager(listContainer, layout, headerText, null);
        iv_remove.setClickable(false);
    }

    private void initData() {
        dialog.startAnimation();
        String url = "https://api.randomuser.me/?results=50&nat=us,dk,fr,gb&seed=qux";
        OkHttpUtils.get()
                .url(url)
                .build()
                .execute(
                        new GenericsCallback<RandomUserResults>(new JsonGenericsSerializator()) {
                            @Override
                            public void onError(Call call, Exception e, int id) {
                                dialog.stopAnimation();
                                dialog.setVisibility(Component.HIDE);
                                ToastDialog dialog = new ToastDialog(AddressBookAbility.this);
                                dialog.setDuration(1500);
                                dialog.setText("请求失败");
                                dialog.show();
                            }

                            @Override
                            public void onResponse(RandomUserResults response, int id) {
                                dialog.stopAnimation();
                                dialog.setVisibility(Component.HIDE);
                                if (response != null) {
                                    randomUsers = sortUsers(Arrays.asList(response.results));
                                    setPeople(randomUsers);
                                    iv_remove.setClickable(true);
                                }
                            }
                        });
    }

    private List<Person> sortUsers(List<Person> users) {
        Collections.sort(users, (lhs, rhs) -> {
            if (lhs.name.last.equalsIgnoreCase(rhs.name.last)) {
                return lhs.name.first.compareToIgnoreCase(rhs.name.first);
            }

            return lhs.name.last.compareToIgnoreCase(rhs.name.last);
        });
        return users;
    }

    /**
     * setPeople
     *
     * @param people people
     */
    public void setPeople(List<Person> people) {
        sections.clear();
        // sort people into buckets by the first letter of last name
        char alpha = 0;
        Section currentSection = null;
        for (Person person : people) {
            if (person.name.last.charAt(0) != alpha) {
                if (currentSection != null) {
                    sections.add(currentSection);
                }

                currentSection = new Section();
                alpha = person.name.last.charAt(0);
                currentSection.alpha = String.valueOf(alpha);
            }

            if (currentSection != null) {
                currentSection.people.add(person);
            }
        }
        sections.add(currentSection);
        for (int i = 0; i < sections.size(); i++) {
            getStickyList(i, sections.get(i).alpha, sections.get(i).people);
        }
        adapter = new AddressBookDemoAdapter(this, dataList);
        listContainer.setItemProvider(adapter);
        headerDecor.setDataList(dataList,true);
    }

    private static class Section {
        String alpha;
        ArrayList<Person> people = new ArrayList<>();
    }

    /**
     * 拼接数据
     *
     * @param index index
     * @param section section
     * @param person person
     */
    public void getStickyList(int index, String section, ArrayList<Person> person) {
        appendSection(index, section, person);
    }

    private void appendSection(int index, String section, ArrayList<Person> person) {
        int ratio;
        ratio = person.size() + 2;
        ItemModel itemModel = null;
        int headIndex = ratio * index;
        itemModel = new HeaderModel(section + "", "", HeaderModel.TYPE_45vp, headIndex,0);
        dataList.add(itemModel);
        for (int i = 0; i < person.size(); i++) {
            itemModel = new ItemModel(section+"", capitalize(person.get(i).name.last) + ", " +
                    capitalize(person.get(i).name.first), false, false, false, true, headIndex + i + 2,0);
            dataList.add(itemModel);
        }
    }

    private String capitalize(String s) {
        if (s != null && s.length() > 0) {
            return s.substring(0, 1).toUpperCase(locale) + s.substring(1);
        }

        return "";
    }
}
